//import angular core
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';

//import third package
import 'rxjs/add/operator/toPromise';

//import class
import { Food } from '../domain/food';

@Injectable()
export class FoodService {
  private api_url = 'http://localhost:3000/foods';
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(private http: Http) { }

  //select all Foods
  getFoods(): Promise<Food[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Food[])
      .catch(this.handleError);
  }

  //select Food by id
  getFoodById(id: number): Promise<Food> {
    const url = `${this.api_url}/${id}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Food)
      .catch(this.handleError);
  }

  //create a Food
  createFood(food: Food): Promise<Food> {
    const url = `${this.api_url}`;
    return this.http
      .post(url, JSON.stringify(food), { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Food)
      .catch(this.handleError);
  }

  //update a Food
  updateFood(food: Food): Promise<Food> {
    const url = `${this.api_url}/${food.id}`;
    return this.http
      .put(url, JSON.stringify(food), { headers: this.headers })
      .toPromise()
      .then(() => food)
      .catch(this.handleError);
  }

  //delete a Food
  deleteFood(food: Food): Promise<void> {
    const url = `${this.api_url}/${food.id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}
